package com.zkjl.protect_business.utils;

import javax.servlet.ServletException;
import java.io.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipUtil {
    /**
     * 压缩文件
     * @param files 键值对-》（文件名：文件链接）
     * @param outputStream
     * @throws Exception
     * @throws IOException
     */
    public static void zipFile(List<File> files,ZipOutputStream outputStream) {
        try {
            for (File file :files) {
                try {
                    InputStream is = new FileInputStream(file);
                    zipFile(is,file.getName(), outputStream);
                    file.delete();
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    /**
     * 将文件写入到zip文件中
     * @param is
     * @param outputstream
     * @throws Exception
     */
    public static void zipFile(InputStream is, String fileName, ZipOutputStream outputstream) throws IOException, ServletException {
        try {
            if (is != null) {
                BufferedInputStream bInStream = new BufferedInputStream(is);
                ZipEntry entry = new ZipEntry(fileName);
                outputstream.putNextEntry(entry);
                int len = 0 ;
                byte[] buffer = new byte[10 * 1024];
                while ((len = is.read(buffer)) > 0) {
                    outputstream.write(buffer, 0, len);
                    outputstream.flush();
                }
                outputstream.closeEntry();//Closes the current ZIP entry and positions the stream for writing the next entry
                bInStream.close();//关闭
                is.close();
            } else {
                throw new ServletException("文件不存在！");
            }
        } catch (IOException e) {
            throw e;
        }
    }

}
